<template>
  <view class="user-detail-page">
    <!-- 顶部背景 -->
    <view class="header-background">
      <view class="back-button" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <text class="page-title">个人资料</text>
    </view>

    <!-- 用户头像区域 -->
    <view class="avatar-section">
      <image class="user-avatar" :src="userInfo.avatar || '/static/images/user1.png'" mode="aspectFill" @click="previewAvatar"></image>
      <view class="avatar-edit" @click="editAvatar">
        <text class="edit-icon">📷</text>
        <text class="edit-text">更换头像</text>
      </view>
    </view>

    <!-- 用户信息卡片 -->
    <view class="info-card">
      <!-- 基本信息 -->
      <view class="info-section">
        <text class="section-title">基本信息</text>
        
        <view class="info-item">
          <text class="info-label">用户ID</text>
          <text class="info-value">{{ userInfo.userId || '--' }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">用户名</text>
          <text class="info-value">{{ userInfo.userName || '--' }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">真实姓名</text>
          <text class="info-value">{{ userInfo.name || '--' }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">性别</text>
          <text class="info-value">{{ userInfo.gender || '--' }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">出生日期</text>
          <text class="info-value">{{ formatDate(userInfo.birthDate) }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">手机号码</text>
          <text class="info-value">{{ formatPhone(userInfo.phone) }}</text>
        </view>
      </view>

      <!-- 统计信息 -->
      <view class="stats-section">
        <text class="section-title">统计信息</text>
        <view class="stats-grid">
          <view class="stat-item">
            <text class="stat-number">{{ stats.subscriptions || 0 }}</text>
            <text class="stat-label">客户</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ stats.followers || 0 }}</text>
            <text class="stat-label">日程</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ stats.visitors || 0 }}</text>
            <text class="stat-label">提议</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ stats.favorites || 0 }}</text>
            <text class="stat-label">历史</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="change-pwd-btn" @click="changePassword">修改密码</button>
      <button class="edit-btn" @click="editProfile">编辑资料</button>
    </view>
  </view>
</template>

<script>
import { getUserInfo, updateUserInfo } from '@/api/user.js'

export default {
  data() {
    return {
      userInfo: {
        userId: '',
        userName: '',
        name: '',
        avatar: '',
        gender: '',
        birthDate: '',
        phone: ''
      },
      stats: {
        subscriptions: 10,
        followers: 8,
        visitors: 0,
        favorites: 21
      }
    }
  },
  
  onLoad() {
    this.loadUserInfo()
  },
  
  onShow() {
    // 每次显示页面时重新加载用户信息，确保编辑后的信息能及时更新
    this.loadUserInfo()
  },
  
  methods: {
    async loadUserInfo() {
      const userId = uni.getStorageSync('userId')
      if (userId) {
        try {
          const res = await getUserInfo(userId)
          if (res && res.code === 1000 && res.data) {
            this.userInfo = { ...this.userInfo, ...res.data }
          }
        } catch (error) {
          console.error('获取用户信息失败:', error)
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          })
        }
      }
    },
    uploadAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const filePath = res.tempFilePaths[0];
          uni.getFileInfo({
            filePath,
            success: (info) => {
              if (info.size > 5 * 1024 * 1024) {
                uni.showToast({ title: '图片不能超过5MB', icon: 'none' });
                return;
              }
              uni.uploadFile({
                url: 'http://localhost:7000/user/user/upload',
                filePath,
                name: 'file',
                success: (uploadRes) => {
                  let data = uploadRes.data;
                  try { data = JSON.parse(data); } catch(e) {}
                  if (data.code === 1000 && data.data) {
                    this.updateUserAvatar(data.data);
                  } else {
                    uni.showToast({ title: data.message || '上传失败', icon: 'none' });
                  }
                },
                fail: () => {
                  uni.showToast({ title: '上传失败', icon: 'none' });
                }
              });
            }
          });
        }
      });
    },
    async updateUserAvatar(newAvatarUrl) {
      const userId = uni.getStorageSync('userId');
      if (!userId) return;
      try {
        const res = await updateUserInfo({
          userId,
          avatar: newAvatarUrl
        });
        if (res && res.code === 1000) {
          this.userInfo.avatar = newAvatarUrl;
          uni.showToast({ title: '头像已更新', icon: 'success' });
        } else {
          uni.showToast({ title: res.message || '头像更新失败', icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '头像更新失败', icon: 'none' });
      }
    },
    previewAvatar() {
      if (this.userInfo.avatar) {
        uni.previewImage({
          urls: [this.userInfo.avatar]
        });
      }
    },
    formatDate(date) {
      if (!date) return '--'
      try {
        const dateObj = new Date(date)
        return dateObj.toLocaleDateString('zh-CN')
      } catch (error) {
        return date
      }
    },
    
    formatPhone(phone) {
      if (!phone) return '--'
      // 手机号码脱敏处理
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    editAvatar() {
      this.uploadAvatar();
    },
    
    editProfile() {
      uni.navigateTo({
        url: '/pages/profile/edit-profile'
      })
    },
    
    changePassword() {
      uni.navigateTo({
        url: '/pages/profile/change-password'
      })
    }
  }
}
</script>

<style scoped>
.user-detail-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #5bb8ac 0%, #4a9c91 100%);
}

.header-background {
  position: relative;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 20px; /* 原来是40px，改为20px */
}

.back-button {
  position: absolute;
  left: 20px;
  top: 50px;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  color: #fff;
  font-size: 20px;
  font-weight: bold;
}

.page-title {
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px; /* 新增，让标题和头像有间距 */
}

.avatar-section {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: -40px;
  z-index: 10;
}

.user-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.avatar-edit {
  margin-top: 10px;
  padding: 6px 16px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.avatar-edit:active {
  transform: scale(0.95);
  background: rgba(255, 255, 255, 1);
}

.edit-icon {
  font-size: 14px;
  margin-right: 4px;
}

.edit-text {
  font-size: 12px;
  color: #5bb8ac;
  font-weight: 500;
}

.info-card {
  margin: 20px;
  background: #fff;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.info-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f8f8f8;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.stats-section {
  margin-top: 20px;
}

.stats-grid {
  display: flex;
  justify-content: space-around;
  margin-top: 15px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.stat-number {
  font-size: 20px;
  font-weight: bold;
  color: #5bb8ac;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

.action-buttons {
  margin: 20px;
  display: flex;
  flex-direction: row;
  gap: 12px;
  justify-content: center;
}

.edit-btn, .change-pwd-btn {
  flex: 1;
  padding: 7px 0;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  border: none; /* 去掉描边 */
  color: #fff;
  background: linear-gradient(135deg, #5bb8ac 0%, #4a9c91 100%);
  transition: all 0.2s;
  box-shadow: none;
}

.edit-btn:active, .change-pwd-btn:active {
  background: #4a9c91;
  color: #fff;
  border: none;
}
</style> 